package com.bw.service.impl;

import com.bw.domain.Role;
import com.bw.domain.TbMenu;
import com.bw.exception.MyRuntimeException;
import com.bw.mapper.RoleMapper;
import com.bw.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author: TaoShiHao
 * @Date: 2025/3/13 10:02
 * @Description:
 **/
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<TbMenu> listMenu() {
        return roleMapper.listMenu();
    }

    @Transactional(rollbackFor = MyRuntimeException.class)
    @Override
    public boolean addOrUpdate(Role role, String menuIds) {


        try {
            if (role.getId() == null) {
                //如果id 为空则是添加
                roleMapper.addRole(role);
            } else {
                //修改
                roleMapper.update(role);
            }
            roleMapper.deleteRoleMenu(role.getId());
            if (!StringUtils.isEmpty(menuIds)) {
                String[] split = menuIds.split( ",");
                for (int i = 0; i < split.length; i++) {
                    roleMapper.addRoleMenu(role.getId(), split[i]);
                }
            }
            return true;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Role checkRoleName(String roleName) {
        return roleMapper.checkRoleName(roleName);
    }

    @Override
    public List<Integer> getMenuIdByRoleId(Integer id) {
        return roleMapper.getMenuIdByRoleId(id);
    }
}
